﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel; 
namespace Skynet.ServiceImplementation
{
    [ServiceBehavior(InstanceContextMode= InstanceContextMode.Single)]
    public class SkynetNotifierService : Skynet.ServiceContracts.ISkynetNotifierService
    {
        private System.Collections.Hashtable _Suscribers;
        private System.Timers.Timer _Timer;
        public SkynetNotifierService()
        {
            _Suscribers = new System.Collections.Hashtable();
            _Timer = new System.Timers.Timer(4000);
            _Timer.Elapsed += (C,S)=> Notification();
            _Timer.Start(); 
        }
        public void Suscription(Guid id)
        {
            var call =  OperationContext.Current.GetCallbackChannel<ServiceContracts.ISkynetNotifierCallBack>();
            _Suscribers.Add(id, call);    
        }
        public void Notification()
        {
            _Timer.Stop();            
            foreach (var item in this._Suscribers.Values)

            {

                var sitem= (System.ServiceModel.IServiceChannel)item;
                if (sitem.State == CommunicationState.Faulted)
                { 
                }
                //var t = new target();
                //InstanceContext context = new InstanceContext(t);
                //var duplex = new DuplexChannelFactory<SkynetProxy.ISkynetNotifierService>(t, "NetTcpBinding_ISkynetNotifierService");
                ////Uri uri = new Uri(@"net.tcp://localhost:7005/callbackchannel");
                ////(()duplex.Endpoint.Binding).ClientBaseAddress = uri;

                //var service = duplex.CreateChannel();
                //service.Suscription(Guid.NewGuid());
                Console.WriteLine("send notification");
                ((ServiceContracts.ISkynetNotifierCallBack)item).SendNotify("notification ");
            }
            _Timer.Start();
        }
    }
}
